<template>
	<view class="container">
		<AddressSelect :data="totalDetail.address"></AddressSelect>
		<view v-if="Object.keys(totalDetail).length" class="content">
			<view class="ctn-item">
				<view class="ctn-title">
					订单详情
				</view>
			</view>
			<view class="ctn-item">
				<view class="tips">
					单价
				</view>
				<view class="txt">
					￥{{orderType === 1 ? sizeList.price : totalDetail.size_data.price}}
				</view>
			</view>
			<view class="ctn-item">
				<view class="tips">
					份数
				</view>
				<NumberBox v-model="buyNum" :asyncChange="false" @change="changeBuyNum"></NumberBox>
			</view>
			<view v-if="orderType === 1" class="ctn-item">
				<view class="tips">
					证件照尺寸
				</view>
				<view class="txt">
					{{sizeList.name}}
				</view>
			</view>
			<view v-else class="ctn-item">
				<view class="tips">
					相片尺寸
				</view>
				<view class="txt">
					{{totalDetail.size_data.name + totalDetail.size_data.describe}}
				</view>
			</view>
			<view class="ctn-item">
				<view class="tips">
					邮费 <image class="icon-img" src="@/static/img/unknow.png" mode="aspectFit"></image>
				</view>
				<view class="txt">
					￥{{totalDetail.goods_fee}}
				</view>
			</view>
			<view class="ctn-item" @click="handleShowCoupon">
				<view class="tips">
					优惠劵
				</view>
				<view class="txt" :style="{color: totalDetail.discount_id && totalDetail.discount_id !== -1 ? '#FF7300' : ''}">
					{{totalDetail.discount_id && totalDetail.discount_id !== -1 ? '-' + totalDetail.discount_price : '无可用优惠'}}
					<span class="icon">></span>
				</view>
			</view>
			<view class="ctn-item">
				<view class="tips">
					快递方式
				</view>
				<view class="txt">
					顺丰速运
				</view>
			</view>
			<view class="ctn-item">
				<view class="total-price">
					<text class="price-tips">
						合计：
					</text>
					<view class="price">
						￥<span>{{totalDetail.allprices}}</span>
					</view>
				</view>
			</view>
		</view>

		<view v-if="Object.keys(totalDetail).length" class="footer safe-btm">
			<view class="left">
				<view class="total-price">
					<text class="price-tips">
						合计：
					</text>
					<view class="price">
						￥<span>{{totalDetail.allprices}}</span>
					</view>
				</view>
				<view class="coupon" v-if="Number(totalDetail.discount_price)">
					共减￥{{totalDetail.discount_price}}
				</view>
			</view>
			<view class="submit-btn" @click="handleSubmit">
				立即支付
			</view>
		</view>

		<CouponPopup v-model="showCoupon" :list="totalDetail.discount_list" :default-id="totalDetail.discount_id"
			@confirm="handleSelectCoupon" />
	</view>
</template>

<script>
	import {
		IdPhotoApi,
		OrderApi,
		UserApi
	} from '@/api';
	import {
		ID_PHOTO_API,
		ID_PHOTO_KEY,
	} from '@/config/request.js';
	import {
		mapGetters
	} from 'vuex';
	import AddressSelect from './components/AddressSelect.vue';
	import NumberBox from './components/NumberBox.vue';
	import CouponPopup from './components/CouponPopup.vue';
	import {
		toPromise,
		uploadFile
	} from '@/utils/util';
	export default {
		components: {
			AddressSelect,
			NumberBox,
			CouponPopup,
		},
		data() {
			return {
				orderTypeList: [{
						key: 1,
						title: '证件照·支付',
						sizeName: '证件照尺寸'
					},
					{
						key: 2,
						title: '照片冲印·支付',
						sizeName: '照片尺寸'
					},
				],
				orderType: 0, // 订单类型 1 证件照 2 照片
				// 选中的照片底色索引
				selectIdPhotoIdx: 0,
				// 购买数量
				buyNum: 1,
				// 商品列表
				goodsList: [],
				// 总计结果
				totalDetail: {
					// 地址
					address: {},
				},
				// 展示优惠券
				showCoupon: false,
				// 选中优惠券
				selectCoupon: {},
			}
		},
		computed: {
			...mapGetters(['sizeList', 'userInfo', 'photoList']),
		},
		onLoad({
			imageSize,
			selectIdPhotoIdx,
			orderType
		}) {
			// 订单类型
			this.orderType = Number(orderType)
			// 证件照的数据索引
			if (selectIdPhotoIdx) this.selectIdPhotoIdx = selectIdPhotoIdx - 1
			// 照片ID
			if (imageSize) this.imageSize = Number(imageSize)
			// 设置标题
			uni.setNavigationBarTitle({
				title: this.orderTypeList[this.orderType - 1].title
			})
			this.initData()
		},
		onShow() {
			this.getPrice()
		},
		methods: {
			/** 
			 * 初始化数据
			 */
			initData() {
				this.getAddress()
				if (this.orderType === 1) this.goodsList = [this.$store.state.idPhoto.userIdPhoto[this.selectIdPhotoIdx]]
			},
			/**
			 * 获取价格
			 */
			getPrice() {
				return new Promise(async (resolve, reject) => {
					try {
						this.$showLoading()
						const res = await IdPhotoApi.GoodsBuyNow(this.getPriceForm())
						this.totalDetail = res
						uni.hideLoading()
					} catch (err) {
						console.log('获取价格失败= ', err);
						uni.hideLoading()
						this.$showToast(err || '获取价格失败')
					}
				})
			},
			/**
			 * 获取价格表单
			 */
			getPriceForm() {
				let form = {
					type: 1,
					file_type: this.orderType,
				}
				// 地址
				if (Object.keys(this.totalDetail.address).length) form.address_id = this.totalDetail.address.address_id
				// 代金券
				if (this.selectCoupon.id) form.voucher_id = this.selectCoupon.id
				if (this.orderType === 1) {
					// 证件照
					form.doc_json = JSON.stringify({
						user_id: this.userInfo.user_id,
						documentSize: this.sizeList.id,
						documentConfig: this.sizeList.one === 1 ?
							this.sizeList.configs[0].id : this.sizeList.configs[this.selectIdPhotoIdx].id,
						data: [{
							file: this.goodsList[0].file_name,
							num: this.buyNum,
						}]
					})
				} else if (this.orderType === 2) {
					// 相片
					form.doc_json = JSON.stringify({
						user_id: this.userInfo.user_id,
						imageSize: this.imageSize,
						data: this.photoList.map(item => {
							return {
								file: item.path,
								num: this.buyNum,
							}
						})
					})
				}
				return form
			},
			/**
			 * 获取下单表单
			 */
			async getPayForm() {
				try {
					let form = {
						type: 'buynow_doc',
						action: 'submit_order',
						file_type: this.orderType,
						pay_code: 'weixin',
						ship_type: 1,
						address_id: this.totalDetail.address.address_id
					}
					// 代金券
					if (this.selectCoupon.id) form.voucher_id = this.selectCoupon.id
					if (this.orderType === 1) {
						const files = await this.getNoWatermark()
						// 证件照
						form.doc_json = JSON.stringify({
							user_id: this.userInfo.user_id,
							documentSize: this.sizeList.id,
							documentConfig: this.sizeList.one === 1 ?
								this.sizeList.configs[0].id : this.sizeList.configs[this.selectIdPhotoIdx].id,
							data: [{
								file: files.result.path, // 证件照无水印
								num: this.buyNum,
							}]
						})
					} else if (this.orderType === 2) {
						// 相片
						form.doc_json = JSON.stringify({
							user_id: this.userInfo.user_id,
							imageSize: this.imageSize,
							data: this.photoList.map(item => {
								return {
									file: item.path,
									num: this.buyNum,
								}
							})
						})
					}
					return Promise.resolve(form)
				} catch (err) {
					console.log("获取下单表单失败", err);
					return Promise.reject(err)
				}
			},
			// 选中优惠券
			handleSelectCoupon(e) {
				this.selectCoupon = e
				this.getPrice()
			},
			// 展示优惠券选择
			handleShowCoupon() {
				if (this.totalDetail.discount_id === -1 || !this.totalDetail.discount_id)
					return
				this.showCoupon = true
			},
			// 挂载监听
			handleChangeAddress() {
				// 选中地址
				uni.$on('selectAddress', (res) => {
					this.totalDetail.address = res
				})
			},
			// 获取地址
			getAddress() {
				// 挂载更改地址
				this.handleChangeAddress()
			},
			// 改变购买数量
			changeBuyNum() {
				this.getPrice()
			},
			// 支付
			async handleSubmit() {
				try {
					this.$showLoading()
					const form = await this.getPayForm()
					const orderRes = await IdPhotoApi.CreatOrderInfo(form)
					this.clearData()
					const payInfoRes = await OrderApi.MiniPayOrder({
						order_id: orderRes.order.order_id,
						openid: this.$store.getters['token']
					})
					const res = await toPromise(uni.requestPayment, {
						provider: 'wxpay',
						...payInfoRes.payinfo,
					})
					uni.hideLoading()
					this.$showToast('支付成功', 2000, true)
					const timer = setTimeout(() => {
						this.$navTo('pages/mines/myOrder', {}, 'redirectTo')
						clearTimeout(timer)
					}, 2000)
				} catch (err) {
					console.log('handleSubmit= ', err);
					uni.hideLoading()
					this.$showToast(err || err.message || '支付失败', 2000, true)
					const timer = setTimeout(() => {
						this.$navTo('pages/mines/myOrder', {}, 'redirectTo')
						clearTimeout(timer)
					}, 2000)
				}
			},
			/** 
			 * 获取无水印证件照
			 */
			getNoWatermark() {
				return new Promise(async (resolve, reject) => {
					try {
						const res = await toPromise(uni.request, {
							url: ID_PHOTO_API + 'take_cut_pic_v2',
							method: 'POST',
							data: {
								file_name: this.goodsList[0].file_name,
								app_key: ID_PHOTO_KEY,
							},
						})
						if (res.data.data.code === 200 || res.data.data.code === 201) {
							// 下载到本地
							const downloadRes = await toPromise(uni.downloadFile, {
								url: res.data.data.file_name_list || res.data.data.file_name
							})
							// 上传到服务器
							const files = await uploadFile({
								path: downloadRes.tempFilePath
							}, false)
							return resolve(files)
						} else {
							return reject(new Error(res.data.error || '获取无水印相片失败'))
						}
					} catch (err) {
						reject(err)
					}
				})
			},
			/** 
			 * 清除现有数据
			 */
			clearData() {
				if (this.orderType === 1) {
					// 清除证件照
					this.$store.commit('idPhoto/clearData')
				} else if (this.orderType === 2) {
					// 清除相片
					this.$store.commit('photo/clearData')
				}
			},

		},
	}
</script>

<style lang="scss" scoped>
	.container {
		--footer-height: 110rpx;
		padding: 20rpx;
		padding-bottom: calc(20rpx + var(--footer-height) + constant(safe-area-inset-bottom));
		padding-bottom: env(20rpx + var(--footer-height) + constant(safe-area-inset-bottom));
	}

	.content {
		margin-top: 30rpx;
		border-radius: 10rpx;
		background: #ffffff;
		box-shadow: 0 16rpx 40rpx 0 #00000008;
	}

	.ctn-item {
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-top: 2rpx solid #f3f3f3;
		font-size: 28rpx;
	}

	.ctn-title {
		color: #000000;
		font-size: 28rpx;
		font-weight: bold;
	}

	.tips {
		display: flex;
		align-items: center;
		color: #767676;
	}

	.txt {
		display: flex;
		align-items: center;
		color: #000000;
	}

	.icon-img {
		margin-left: 10rpx;
		width: 30rpx;
		height: 30rpx;
	}

	.icon {
		margin-left: 5rpx;
		font-size: 28rpx;
		color: #767676;
	}

	.footer {
		position: fixed;
		right: 0;
		bottom: 0;
		left: 0;
		display: flex;
		justify-content: right;
		align-items: center;
		padding-left: 30rpx;
		padding-right: 30rpx;
		height: var(--footer-height);
		border-top: 2rpx solid #f4f4f4;
		background-color: #fff;
		z-index: 999;

		.left {
			margin-left: auto;

			.coupon {
				color: $theme-color;
				font-size: 20rpx;
				text-align: right;
			}
		}
	}

	.total-price {
		display: flex;
		align-items: flex-end;
		font-size: 20rpx;
		margin-left: auto;

		.price-tips {
			color: #606060;
		}

		.price {
			color: $theme-color;

			span {
				font-size: 36rpx;
				line-height: 100%;
			}
		}
	}


	.submit-btn {
		margin-left: 20rpx;
		width: 228rpx;
		height: 70rpx;
		line-height: 70rpx;
		border-radius: 35rpx;
		background: linear-gradient(135deg, #ffb300 4%, #ff6a00 100%);
		color: #ffffff;
		text-align: center;
		font-size: 24rpx;
	}
</style>